#include "ClientList.h"
#include <iostream>
using namespace std;

ClientList::ClientList()
{
	
}

ClientList::~ClientList()
{
}

const	int	ClientList::getIndex(const int ClientSocket)
{
	list<vector<int> >::iterator it = _clientIndex.begin();
	int index = 0;
	int i = 0;
	vector<int>	tmp(2);
	vector<string>	tmpString(5);

	if ((index = isClient(ClientSocket)) >= 0)
	{
		while (i != index)
		{
			i++;
			it++;
		}
		return ((*it)[1]);
	}
	else
	{
		tmp[0] = ClientSocket;
		tmp[1] = 0;
		_clientIndex.push_back(tmp);
		_client.push_back(tmpString);
	}
	return (0);
}

void	ClientList::incIndex(const int ClientSocket)
{
	list<vector<int> >::iterator it = _clientIndex.begin();
	int index = 0;
	int i = 0;
	vector<int>	tmp(2);
	vector<string>	tmpString(5);

	if ((index = isClient(ClientSocket)) >= 0)
	{
		while (i != index)
		{
			i++;
			it++;
		}
		tmp[0] = ClientSocket;
		tmp[1] = ((*it)[1] + 1);
		_clientIndex.insert(it, tmp);
	}
	else
	{
		tmp[0] = ClientSocket;
		tmp[1] = 0;
		_clientIndex.push_back(tmp);
		_client.push_back(tmpString);
	}
}

const	int	ClientList::isClient(const int ClientSocket)
{
	list<vector<int> >::iterator it = _clientIndex.begin();
	int flag = -1;
	int i = 0;

	while ((it != _clientIndex.end()) && (flag == -1))
	{
		if ((*it)[0] == ClientSocket)
			flag = i;
		it++;
		i++;
	}
	return (flag);
}

void	ClientList::manageData(const std::string result, const int ClientSocket)
{
	int index = getIndex(ClientSocket);
	int	tmp = isClient(ClientSocket);
	int i = 0;
	list<vector<std::string> >::iterator it = _client.begin();
	
	while (i < tmp)
	{
		i++;
		it++;
	}
	if (index < 5)
	{
		(*it)[index] = result;
	}
}
